package com.caishi.lkx.user.service.impl;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.caishi.lkx.user.mapper.ConfigMapper;
import com.caishi.lkx.user.model.ConfigModel;
import com.zzw.common.Fetch;
import com.zzw.common.Wrappers;
import com.zzw.common.entity.BaseService;
import com.zzw.common.entity.IBaseMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.function.Function;

/**
 * @Author: huangpeng
 * @Date: 2021/9/23 9:37
 * @Description:
 */
@Service
public class ConfigServiceImpl implements BaseService<ConfigModel, Long> {
    @Resource
    private ConfigMapper configMapper;


    @Override
    public IBaseMapper<ConfigModel, Long> getMapper() {
        return configMapper;
    }

    @Override
    public ConfigModel insert(ConfigModel entity) {
        Assert.notEmpty(entity.getKey());
        ConfigModel old = getMapper().selectOne(Wrappers.lambdaQuery(new ConfigModel())
                .eq(ConfigModel::getKey, entity.getKey()));
        if (old != null) {
            entity.setId(old.getId());
            return this.update(entity);
        }
        return BaseService.super.insert(entity);
    }

    @Override
    public ConfigModel update(ConfigModel entity) {
        Assert.notEmpty(entity.getKey());
        all:
        if (entity.getId() == null) {
            ConfigModel old = getMapper().selectOne(Wrappers.lambdaQuery(new ConfigModel())
                    .eq(ConfigModel::getKey, entity.getKey()));
            if (old != null) {
                entity.setId(old.getId());
                break all;
            }
            return this.insert(entity);
        }
        return BaseService.super.update(entity);
    }

    public Object getValue(String key) {
        return Fetch.fetch(
                        getMapper().selectOne(com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(new ConfigModel())
                                .select(ConfigModel::getValue)
                                .eq(ConfigModel::getKey, key)
                                .eq(ConfigModel::getEnable, true)
                        )).then(conf -> conf == null ? null : conf.getValue())
                .then((Function<String, Object>) JSON::parse)
                .catchFetch((e, d) -> {
                    if (e instanceof JSONException) {
                        return d;
                    }
                    return null;
                })
                .getData();
    }

}
